package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApArticleStaticHtmlService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.CacheConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.LoadBehaviorInfoVO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.List;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleStaticHtmlService apArticleStaticHtmlService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ApArticle> load(ArticleHomeDto dto, Short status) {

        //1.size进行范围判断
        if(dto.getSize() <=0 || dto.getSize() >=1000){
            dto.setSize(10);
        }

        //2.对tag
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //分页助手
        Page<ApArticle> page = new Page<>();
        page.setCurrent(1); //第一页
        page.setSize(dto.getSize());
        page.setSearchCount(false); //不需要操作select count统计总数据量
        return apArticleMapper.selectArticleList(page,dto, status);
    }

    @Override
    public List<ApArticle> load2(ArticleHomeDto dto, Short status, boolean cache) {
        if(cache){
            //走缓存
            String content = stringRedisTemplate.opsForValue()
                    .get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(content)){
                return JSON.parseArray(content,ApArticle.class);
            }
        }

        return load(dto,status);
    }

    @Override
    public Long saveArticle(ArticleDto dto) {
        //1.判断id是否存在 存在代表修改 不存在代表新增
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        if(dto.getId() == null){
            //2.新增 添加三张表的数据 (主表,配置表,内容表) 配置表用默认值
            //主表
            save(apArticle);

            //配置表
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        }else {
            //3.修改 只需要修改两张表 (主表,内容表)
            //主表
            updateById(apArticle);

            //内容表
            apArticleContentMapper.update(null, Wrappers.<ApArticleContent>lambdaUpdate()
                    .eq(ApArticleContent::getArticleId,apArticle.getId())
                    .set(ApArticleContent::getContent,dto.getContent())
            );
        }

        //创建静态页面
        try {
            apArticleStaticHtmlService.createStaticHtml(apArticle,dto.getContent());
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"生成静态页面失败");
        }

        //4.返回主键id
        return apArticle.getId();
    }

    @Override
    public LoadBehaviorInfoVO loadArticleBehavior(ArticleInfoDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取状态
        //1.点赞
        LoadBehaviorInfoVO loadBehaviorInfoVO = new LoadBehaviorInfoVO();

        String userId = user.getId().toString();
        String key =  CacheConstants.LIKES + dto.getArticleId();
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, userId);
        if(member != null && member){
            loadBehaviorInfoVO.setIslike(true);
        }

        //关注
        key =  CacheConstants.FOLLOW_FANS + dto.getAuthorId();
        member = stringRedisTemplate.opsForSet().isMember(key, userId);
        if(member != null && member){
            loadBehaviorInfoVO.setIsfollow(true);
        }
        return loadBehaviorInfoVO;
    }
}
